//index.js

let util = require("../../utils/util.js")
const app = getApp();

let jumpurl = app.jumpurl.url;
let openid;
let nav_id = 2;//当前nav的id
let last_id;//上次数据的最后一条数据的id
let currentpage = 1;//当前页数
let nickname = app.userlist.nickName;
let newslist0 = [];
let city;//当前城市
let district;//当前区域
let moren_city = "徐州";
let zhiding;
let qita;
let activeId;//nav中选中的分类的id
let visitedId = 0;//新闻列表中选中的新闻的id
var animation = wx.createAnimation({
  transformOrigin: "50% 50%",
  duration: 1000,
  timingFunction: "ease",
  delay: 0
})
module.exports = {
  animation: animation
}
Page({
  data: {
    notNone: true,//是否为空 默认非空
    userInfo: "",
    hasUserInfo: "",
    city: "徐州",
    visitedflag: false,//是否已读
    refreshnum: 0,//每次刷新更新数据条数
    refreshFlag: true,//是否显示刷新bar
    greyFlat: false,//是否显示城市提示框
    // optionsflag:false,//是否显示选择频道容器 true--显示  false--不显示
    //模拟数据 nav
    navlist: [{
      id: 0,
      name: "关注",
    },
    {
      id: 1,
      name: "推荐",
    },
    ],
    topnews: [{
      id: 0,
      types: 1,//新闻类型
      title: "网上下拉刷新的例子挺多的，我也用了试成功了一个，但目前发现，当本来listView内容过少不能充满父容器的时候，下拉刷新的头部",
      tag: "置顶",
      subTag: "优米定制",
      num: 100,
      media: ["/pages/index/images/pic0.png", "/pages/index/images/pic0.png", "/pages/index/images/pic0.png"]
    }],
    // 新闻列表测试数据
    newslists: [{
      id: 1,
      types: 0,//新闻类型
      title: "网上下拉刷新的例子挺多的，我也用了试成功了一个，但目前发现，当本来listView内容过少不能充满父容器的时候，下拉刷新的头部",
      tag: "广告",
      subTag: "医学护肤",
      num: 100,
      media: ["images/pic0.png", "images/pic0.png", "images/pic0.png"],
      ad: true
    },
    {
      id: 2,
      types: 1,//新闻类型
      title: "网上下拉刷新的例子挺多的，我也用了试成功了一个，但目前发现，当本来listView内容过少不能充满父容器的时候，下拉刷新的头部",
      tag: "美容护肤",
      subTag: "医学护肤",
      num: 100,
      media: ["images/pic0.png", "images/pic0.png", "images/pic0.png"],
      ad: false
    },

    {
      id: 3,
      types: 2,//新闻类型
      title: "网上下拉刷新的例子挺多的，我也用了试成功了一个，但目前发现，当本来listView内容过少不能充满父容器的时候，下拉刷新的头部",
      tag: "广告",
      subTag: "医学护肤",
      num: 100,
      media: ["images/pic0.png", "images/pic0.png", "images/pic0.png"],
      ad: true
    },
    {
      id: 43,
      types: 3,//新闻类型
      title: "网上下拉刷新的例子挺多的，我也用了试成功了一个，但目前发现，当本来listView内容过少不能充满父容器的时候，下拉刷新的头部",
      tag: "广告",
      subTag: "医学护肤",
      num: 100,
      media: ["images/pic0.png", "images/pic0.png", "images/pic0.png"],
      ad: true
    },
    {
      id: 1,
      types: 4,//新闻类型
      title: "网上下拉刷新的例子挺多的，我也用了试成功了一个，但目前发现，当本来listView内容过少不能充满父容器的时候，下拉刷新的头部",
      tag: "美容护肤",
      subTag: "医学护肤",
      num: 100,
      media: ["images/pic0.png"],
      ad: false
    },
    {
      id: 2,
      types: 5,//新闻类型
      title: "网上下拉刷新的例子挺多的，我也用了试成功了一个，但目前发现，当本来listView内容过少不能充满父容器的时候，下拉刷新的头部",
      tag: "美容护肤",
      subTag: "医学护肤",
      num: 100,
      media: ["images/pic0.png", "images/pic0.png", "images/pic0.png"],
      ad: false
    }
    ],

    activeId: 1,//选中的选项序号
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

  },
  //点击nav
  choseNav: function (e) {
    console.log("dianjile");
    var that = this;
    var act_id = e.currentTarget.dataset.index;
    var this_index = e.currentTarget.dataset.index;
    var this_id = e.currentTarget.dataset.id;
    nav_id = this_id;
    var guanzhu_index = 0;//关注
    if (app.globalData.userInfo) {
      console.log("app.globalData.userInfo");
      console.log(app.globalData.userInfo);
      that.setData({
        notNone: true
      })
    } else {
      console.log("未授权");
      //点击关注按钮
      if (this_index == guanzhu_index) {
        that.setData({
          notNone: false
        })
      } else {
        //点击其他按钮
        that.setData({
          notNone: true
        })
      }
    }

    that.setData({
      activeId: act_id
    })
    //调用接口，请求数据
    //请求接口，获取新闻列表
    wx.request({
      url: util.tuijian_newslist,
      data: {
        openid: app.globalData.openid,
        classid: this_id,
      },
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded" //post
      },
      success: function (res) {
        console.log("新闻列表");
        console.log(res);

        newslist0 = [];
        if (res.data.count != 0) {
          var newslists = res.data.content;
          that.setData({
            newslists: newslists
          })
          for (var i = 0; i < newslists.Length; i++) {
            newslist0.push(newslists[i]);
          }

        }
      },
      fail: function (err) {
        console.log("err" + err);
      }
    })



  },


  onLoad: function () {
    var page = this;
    if (app.globalData.userInfo) {
      console.log("----------已授权----------------")
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true,
        notNone: true
      })
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        page.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          page.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }



    wx.showLoading({
      title: '加载中...',
    })

    setTimeout(function () {
      wx.hideLoading();

    }, 500)



    app.getOpenid().then(function (res) {
      if (res.status == 200) {

        console.log('openid-------------' + wx.getStorageSync('openid'));

        app.globalData.openid = wx.getStorageSync('openid');
        page.setData({
          openid: wx.getStorageSync('openid')
        })



        //访问接口,获取nav
        wx.request({

          url: util.shoueyNav,
          data: {
            openid: app.globalData.openid
          },
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded" //post
          },
          success: function (res) {
            console.log("-----获取nav success-------");
            console.log(res);
            if (res) {
              //有返回值
              var navlist = res.data.daohang;
              activeId = res.data.daohang[1].id;
              page.setData({
                navlist: res.data.daohang,  //上部导航
                topnews: res.data.zhiding,  //置顶数据
                newslists: res.data.tuijian, //推荐数据
              })
            } else {
              console.log("返回nav为空，导航栏为测试数据")
            }

          },
          fail: function (err) {
            console.log("getNav接口调用失败");
          }
        })

      }
    });



    setTimeout(function () {

      page.setData({
        refreshFlag: false
      })
    }, 2500)
    /*******************定位***************/
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res);
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        //45f2637ce0ee391b9f552e20f1816e05
        page.loadCity(longitude, latitude)
      }
    })
  },
  loadCity: function (longitude, latitude) {
    var page = this
    wx.request({
      url: 'https://restapi.amap.com/v3/geocode/regeo?key=45f2637ce0ee391b9f552e20f1816e05&location=' + longitude + ',' + latitude,
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function (res) {
        // success  
        console.log("success")
        console.log(res);
        city = res.data.regeocode.addressComponent.city;
        city = city.split("市")[0];//截取城市名
        district = res.data.regeocode.addressComponent.district;
        console.log(city);
        console.log(district);

        page.setData({
          city: city
        })
        if (city != moren_city) {
          page.setData({
            greyFlag: true
          })
        }
      },
      fail: function () {
        page.setData({ currentCity: "获取定位失败" });
      },

    })
  },
  getUserInfo: function (e) {
    console.log(e)
    app.globalData.userInfo = e.detail.userInfo
    this.setData({

      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },

  /************************** */
  onPullDownRefresh: function () {
    var that = this;

    wx.showNavigationBarLoading(); //在标题栏中显示加载图标
    setTimeout(function () {
      wx.stopPullDownRefresh()
      wx.hideNavigationBarLoading()
    }, 1000)
    console.log("shangla")
    console.log(nav_id);
    wx.request({
      url: util.tuijian_newslist,
      data: {
        class_id: nav_id,
        tag: 1,

      },
      success: function (res) {
        console.log("下拉刷新");
        console.log(res);
        currentpage = currentpage + 1;
        wx.stopPullDownRefresh()
        wx.hideNavigationBarLoading();
        wx.showToast({
          title: '没有更多数据',
          icon: "none"
        })
      }, fail: function (err) {
        console.log(err);
      }
    })


    setTimeout(function () {
      that.setData({
        refreshFlag: true
      })
    }, 1000)
    setTimeout(function () {
      that.setData({
        refreshFlag: false
      })
    }, 3000)
  },
  /*******上拉加载************ */
  onReachBottom: function () {
    console.log("***********到达底部***************")
    var that = this;
    //请求后台，获取数据
    wx.request({
      url: util.tuijian_newslist,
      data: {
        class_id: nav_id,
        tag: 1,
        page: currentpage

      },
      success: function (res) {
        console.log("获取数据...");
        console.log(res);
        currentpage = currentpage + 1;
        wx.showLoading({
          title: '正在加载中...',
        })
        setTimeout(function () {
          wx.hideLoading()

        }, 1000)
        if (res.data.news) {
          var newslist_more = res.data.news;

          for (var i = 0; i < newslist_more.length; i++) {
            newslist0.push(newslist_more[i]);
          }
          console.log(newslist0);
          that.setData({
            newslists: newslist0
          })
        } else {
          setTimeout(function () {
            wx.showToast({

              title: '没有更多数据加载',
              icon: "none"
            })
          }, 1000)
        }
      },
      fail: function () {
        console.log("没有获取数据");
      }
    })





  },
  //关闭城市提示框
  shut: function () {
    var that = this;
    that.setData({
      greyFlag: false,
      city: moren_city
    })
    //请求后台，获取徐州的数据，将城市改为徐州
  },

  //选择城市
  chosecity: function () {
    var that = this;
    // that.setData({
    //   greyFlag:true
    // })
  },

  //申请加盟
  joinIn: function () {
    //跳页
  },

  //进入选择页面
  getmore: function () {
    wx.redirectTo({
      url: '/pages/options/options',
    })
    // wx.navigateTo({
    //   url: '/pages/options/options',
    // })

  },
  //跳转至新闻页面
  newsdetail: function (e) {
    console.log(e);
    var that = this;
    var id = e.currentTarget.dataset.id;

    that.setData({
      visitedflag: true,
      visitedId: e.currentTarget.dataset.id
    })
    wx.navigateTo({
      url: '/pages/detail/detail?newid=' + id,
    })
  },
  //跳转至视频页面
  audiodetail: function (e) {
    console.log(e);
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/audio/audio?newid=' + id,
    })
  },
  //跳转至搜索页
  search: function () {
    wx.navigateTo({
      url: '/pages/search/search',
      success: function (res) {

      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  //onshow
  onShow: function () {
    console.log("index onshow")
  },


})

//下拉刷新图标旋转动画
function updateRefreshIcon() {
  var deg = 0;
  var that = this;
  console.log('旋转开始了.....')
  //创建动画
  var animation = wx.createAnimation({
    duration: 1500
  })
  var timer = setInterval(function () {
    if (!that.data.refreshing)
      clearInterval(timer)
    animation.rotateZ(deg).step();//在Z轴旋转一个deg角度
    deg += 360
    that.setData({
      refreshAnimation: animation.export()
    })
  }, 500);
}
